package com.fsx.serverimmediate.comm;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 一对一聊天
 */
@Component
@ServerEndpoint(value = "/websocket/{uName}",subprotocols = {"protocol"})
public class WebSocket {

    /**
     * 存储在线连接数
     */
    private static final Map<Session,String> SESSION_POOL=new Hashtable<>();
    /**
     * 存储用户关联关系
     */
    private static final Map<Session, Session> SESSION_JOIN  = new Hashtable<>();
    private static final CopyOnWriteArrayList<Session> SESSION_IDLE=new CopyOnWriteArrayList();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uName") String uName) {
        SESSION_POOL.put(session,uName);
        SESSION_IDLE.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        fault(session);
        SESSION_POOL.remove(session);
        SESSION_IDLE.remove(session);
        SESSION_JOIN.remove(session);
    }

    @OnMessage
    public void onMessage(Session session,String message) {
        System.out.println(SESSION_IDLE);
        try {
            String[] array = StringUtils.delimitedListToStringArray(message,"#");
            switch (array[0]){
                case "link":
                    try {
                        Session join=SESSION_IDLE.get((int)(Math.random()*SESSION_IDLE.size()));
                        if(join==session){
                            throw new ArrayIndexOutOfBoundsException();
                        }
                        SESSION_IDLE.remove(join);
                        SESSION_IDLE.remove(session);
                        SESSION_JOIN.put(session,join);
                        SESSION_JOIN.put(join,session);
                        join.getAsyncRemote().sendText("message#"+SESSION_POOL.get(session)+"连接了你");
                        session.getAsyncRemote().sendText("message#"+SESSION_POOL.get(join)+"连接了你");
                    } catch (ArrayIndexOutOfBoundsException e) {
                        session.getAsyncRemote().sendText("message#匹配失败，请稍后尝试");
                    }
                    break;
                case "chat":
                    Session chat=SESSION_JOIN.get(session);
                    if(chat!=null&&chat.isOpen()){
                        chat.getAsyncRemote().sendText("chat#"+array[1]);
                    }else {
                        session.getAsyncRemote().sendText("message#对方已掉线");
                    }
                    break;
                case "fault":
                    fault(session);
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
//            SESSION_JOIN.remove(session);
//            SESSION_IDLE.add(session);
        }
    }

    private void fault(Session session) {
        Session fault=SESSION_JOIN.get(session);
        SESSION_JOIN.remove(session);
        if(fault!=null&&fault.isOpen()){
            SESSION_JOIN.remove(fault);
            SESSION_IDLE.add(fault);
            if(session.isOpen()){
                SESSION_IDLE.add(session);
            }
            fault.getAsyncRemote().sendText("message#"+SESSION_POOL.get(session)+"断开连接");
            session.getAsyncRemote().sendText("message#"+SESSION_POOL.get(fault)+"断开连接");
        }
    }


}
